package org.example.dao;

import org.example.domain.User;
import org.example.orm.RowMapper;
import org.example.orm.SqlSession;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author hsc
 * @date 2024-02-02
 * @Description 数据处理层
 */
public class UserDao {

    private SqlSession sqlSession = new SqlSession();

    public void insert(User user) {
//        方式一：使用对象传递sql的参数
        String sql = "insert into users values(#{uid},#{uname},#{upass})";
        sqlSession.insert(sql, user);
        //方式二：使用动态数组传递参数
//        String sql = "insert into users values(?,?,?)";
//        sqlSession.insert(sql, 2,"hsc",8888);
    }

    public void deleteUser(int uid) {
        String sql = "delete from users where uid = #{uid}";
        sqlSession.deleteUser(sql, uid);
    }

    public void updateUser(User user) {
        String sql = "update users set uname=#{uname},upass=#{upass} where uid=#{uid}";
        sqlSession.updateUser(sql, user);
    }

    /**
     * 方式一：查询一条数据，基于策略模式的写法
     *
     * @param uid
     * @return
     */
    public User selectOne(int uid) {
        //1、sqlSession对象查询数据
        //构建sql
        String sql = "select * from users where uid = ?";
        //sqlSession对象查询数据
        //TODO 根据查询到的结果集封装返回具体的数据 这里用到了一个设计模式：策略模式
        RowMapper rowMapper = new RowMapper() {
            @Override
            public <T> T mapperRow(ResultSet resultSet) throws SQLException {
                //根据需要的具体对象进行返回
                User user = new User();
                user.setUid(resultSet.getInt("uid"));
                user.setUname(resultSet.getString("uname"));
                user.setUpass(resultSet.getInt("upass"));
                return (T) user;
            }
        };
        return sqlSession.selectOne(sql, rowMapper, uid);
    }

    /**
     * 查询所有的数据方式一：查询数据，基于策略模式的写法
     * * @return
     */
    public List<User> selectList() {
        String sql = "select * from users";
        //TODO 根据查询到的结果集封装返回具体的数据 这里用到了一个设计模式：策略模式
        RowMapper rowMapper = new RowMapper() {
            @Override
            public <T> T mapperRow(ResultSet resultSet) throws SQLException {
                //根据需要的具体对象进行返回
                User user = new User();
                user.setUid(resultSet.getInt("uid"));
                user.setUname(resultSet.getString("uname"));
                user.setUpass(resultSet.getInt("upass"));
                return (T) user;
            }
        };
        return sqlSession.selectList(sql, rowMapper);
    }

    /**
     * 查询一条数据方式二：可以用任意类型进行参数的传递，并且返回对应指定的类型的对象
     *
     * @param uid
     * @return
     */
    public User selectOneNew(int uid) {
        String sql = "select * from users where uid = #{uid}";
        User user = sqlSession.selectOne(sql, uid, User.class);
        return user;
    }
}
